<template>
    <l-layout class="l-tab-page" v-if="!lr_loadPage" :left="240" v-loading="syncLoading" element-loading-text="拼命同步中...">
        <template #left>
            <l-panel :title="$t('公司信息')" style="padding-right:0;" >
                <el-tree class="learun-tree" v-loading="treeLoading" :data="lr_companyTree" default-expand-all :expand-on-click-node="false"  @node-click="handleNodeClick">
                    <span class="lr-tree-node"  slot-scope="{node}">
                        <i class="learun-icon-co"></i>
                        {{ $t(node.label) }}
                    </span>
                </el-tree>
            </l-panel>
        </template>
        <l-panel style="padding-left:0;" >
            <template #toolLeft >
                <div class="l-panel--item" >
                    <l-tree-select
                        v-model="departmentId"
                        :placeholder="$t('please select部门')"
                        :options="lr_departmentTree(lr_departments[companyId])"
                        size="mini"

                        @change="handleChangeDept"
                        >
                    </l-tree-select>
                </div>
                <div class="l-panel--item" >
                    <el-input :placeholder="$t('please enter姓名/账号/电话')"  @keyup.enter.native="hanleSearch" v-model="searchWord" size="mini" >
                        <el-button @click="hanleSearch" slot="append" icon="el-icon-search"></el-button>
                    </el-input>
                </div>
            </template>
            <template #toolRight >
                <l-tool-btns @click="handleAdd()" >
                    <el-button-group v-if="lr_hasPageAuth('Sync','buttons')">
                        <!-- <el-button type="warning" size="mini" @click="openFrom()" icon="el-icon-refresh">{{ $t("同步") }}</el-button> -->
                    </el-button-group>
                    <l-excel-btns></l-excel-btns>
                    <el-button-group v-if="lr_hasPageAuth('ExportExcel','buttons')">
                        <el-button size="mini" icon="el-icon-download"
                            @click="handleDownLoad"
                        >{{ $t('导出') }}</el-button>
                    </el-button-group>
                </l-tool-btns>
            </template>
            <l-table 
                :columns="lr_getPageColumns(columns)" 
                :dataSource="tableData" 
                :loading="tableLoading"
                row-key="f_UserId"
                :isPage="true"
                :pageTotal="tableTotal"
                :tablePage.sync="tableCurrentPage"

                @loadPageData="turnTablePage"
                >
                <template v-slot:f_Gender="scope" >
                    <el-tag v-if="scope.row.f_Gender == 1" size="mini" type="success">{{ $t('男') }}</el-tag>
                    <el-tag v-else size="mini" type="danger">{{ $t('女') }}</el-tag>
                </template>
                <template v-slot:f_CompanyId="scope" >
                    {{(lr_companyList.find(t=>t.f_CompanyId == scope.row.f_CompanyId) || {}).f_FullName || ''}}
                </template>
                <template v-slot:f_DepartmentId="scope" >
                    {{lr_departmentName(lr_departments[scope.row.f_CompanyId] || [],scope.row.f_DepartmentId)}}
                </template>
                <template v-slot:f_EnabledMark="scope" >
                    <el-switch
                        :active-value="1"
                        :inactive-value="0"
                        v-model="scope.row.f_EnabledMark"
                        @change="handleEnableChange(scope.row)"
                        >
                    </el-switch>
                </template>
                <l-table-btns :btns="tableBtns" @click="lr_handleTableBtnClick" ></l-table-btns>
            </l-table>
        </l-panel>

        <l-dialog 
            :title="formTitle"
            :visible.sync="formVisible"
            :height="600"
            :width="720"
            @ok="handleSave"
            @close="handleCloseForm"
            @opened="handleOpenedForm"
            >
            <my-form ref="form" ></my-form>       
        </l-dialog>
        <!-- 同步操作 -->
        <l-dialog :title="$t(syncTitle)"
            :visible.sync="syncVisible"
            :height="150"
            :width="400"
            @ok="handleSync"
            >
            <div class="l-from-body">
                <el-form size="small" ref="syncForm" label-width="100px">
                    <el-col :span="24">
                        <el-form-item :label="$t('截止时间')" prop="startTime">
                            <l-date format="yyyy-MM-dd HH:mm:ss" dateType="datetime" :clearable="true"
                            v-model="startTime" :placeholder="$t('please select')"/>
                        </el-form-item>
                    </el-col>
                </el-form>
            </div>
        </l-dialog>

    </l-layout>
</template>

<script>
const api = window.$api.organization.user
import MyForm from './form'

export default {
    components: {
        MyForm
    },
    data () {
        return {
            lr_isPage:true,

            treeLoading:false,

            //query
            searchWord:'',
            searchTableData:null,

            tableLoading:false,
            columns: [
                {label:'姓名',prop:'f_RealName',minWidth:'110'},
                {label:'账号',prop:'f_Account',width:'110'},
                {label:'手机',prop:'f_Mobile',width:'108'},
                {label:'公司',prop:'f_CompanyId',width:'120'},
                {label:'部门',prop:'f_DepartmentId',width:'140'},
                {label:'性别',prop:'f_Gender',width:'80',align:'center'},
                {label:'状态',prop:'f_EnabledMark',width:'64',align:'center'},
                //{label:'排序',prop:'f_SortCode',width:'60',align:'center'},
            ],
            tableBtns:[
                {prop:'Edit',label:this.$t('Edit'),width:40},
                {prop:'Delete',label:this.$t('Delete'),width:40},
                {prop:'ResetPassword',label:this.$t('Reset password'),width:60}
            ],
            tableData:[],
            tableTotal:0,
            tablePageSize:50,
            tableCurrentPage:1,
            companyId:'',
            departmentId:'',
            departmentLoading:false,

            formVisible:false,
            formTitle:'',
            formEditRow:null,
            formEdit:false,

            syncLoading:false,
            syncVisible:false,
            syncTitle:this.$t("指定更新截止时间"),
            startTime:""
        }
    },
    computed:{
    },
    mounted () {
        this.init()
    },
    methods:{
        async init(){
            this.loadTableData()
            this.treeLoading = true
            await this.lr_loadCompanys()
            this.treeLoading = false
        },
        loadTableData(isNotFirst){
            if(!isNotFirst){
                this.tableCurrentPage = 1;
            }
            this.tableLoading = true;
            let queryData = {
                rows:this.tablePageSize,
                page:this.tableCurrentPage,
                sidx:'F_SortCode ASC,F_CreateDate DESC',
                keyword:this.searchWord,
                companyId:this.companyId,
                departmentId:this.departmentId
            }
            api.getPage(queryData).then(res=>{
                const data = this.$deepClone(res.data.data)
                data.rows.forEach(item => {
                    if(item.f_CompanyId){
                        this.lr_loadDepartments(item.f_CompanyId)
                    }
                })
                this.tableData = data.rows
                this.tableTotal = data.records
                this.tableLoading = false
            }).catch(()=>{
                this.tableData = []
                this.tableLoading = false
            })
        },
        turnTablePage({rows}){
            this.tablePageSize = rows
            this.loadTableData(true)
        },
        handleNodeClick(data) {
            this.companyId = data.value
            this.departmentId = ''
            this.lr_loadDepartments(this.companyId)
            this.loadTableData()
        },
        handleChangeDept(){
            this.loadTableData()
        },
        hanleSearch(){
            this.loadTableData()
        },
        handleEnableChange(row){
            api.updateState(row.f_UserId,row.f_EnabledMark).then(()=> {
                this.$message({
                    type: 'success',
                    message: this.$t('更新成功!')
                })
            })
        },
        handleDownLoad(){
            this.lr_downFile('organization/users/export','用户导出')

            //this.$downFile(`${this.apiUrl}organization/users/export?token=${this.token}`)
        },
        handleAdd(){
            this.formEdit = false;
            this.showForm('Add用户');
        },
        handleEdit($index,row){
            this.formEdit = true;
            this.formEditRow = row;
            this.showForm('Edit用户');
        },
        handleDelete($index,row){
            this.$confirm(this.$t('This operation will permanently delete the data. Do you want to continue?'), this.$t('Tips'), {
                confirmButtonText: this.$t('confirm'),
                cancelButtonText: this.$t('cancel'),
                type: 'warning'
            }).then(() => {
                api.remove(row.f_UserId).then(()=> {
                    this.$message({
                        type: 'success',
                        message: this.$t('Delete  success')
                    })
                    this.loadTableData()
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: this.$t('Delete has been canceled')
                })        
            })
        },
        async handleSave(showLoading,hideLoading){
            showLoading('保存数据')
            if(await this.$refs.form.validateForm()){
                const postData = this.$refs.form.getForm()
                if(this.formEdit){// 修改数据
                    await api.update(this.formEditRow.f_UserId,postData)
                    this.$message({
                        type: 'success',
                        message: this.$t('更新成功!')
                    })
                }
                else{// Edit data
                    postData.user.f_Password = this.$md5(postData.user.f_Password)
                    await api.add(postData)
                    this.$message({
                        type: 'success',
                        message: this.$t('添加成功!')
                    })
                }
                this.formVisible = false
                this.loadTableData()
            }
            hideLoading()
        },

        async handleOpenedForm(showLoading,hideLoading){
            if(this.formEdit){
                showLoading('Loading data...')
                const data = await this.$awaitWraper(api.get(this.formEditRow.f_UserId))
                this.$refs.form.setForm(data)
                hideLoading()  
            }
        },

        handleCloseForm(){
            this.$refs.form.resetForm();
        },
        showForm(text){
            this.formTitle = text;
            this.formVisible = true;
        },

        // 
        handleResetPassword($index,row){
            this.$confirm(`${this.$t("是否Reset用户")}【${row.f_RealName}】${this.$t("password?")}`, this.$t('Tips'), {
                confirmButtonText: this.$t('confirm'),
                cancelButtonText: this.$t('cancel'),
                type: 'warning'
            }).then(() => {
                api.resetPassword(row.f_UserId).then(()=> {
                    this.$message({
                        type: 'success',
                        message: this.$t('Reset成功!')
                    })
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: this.$t('已cancelReset')
                })      
            })
        },
        //用户同步
        openFrom(){
            this.syncVisible = true
        },
        async handleSync(){
            this.$confirm(this.$t('此操作将开始同步用户信息, 是否继续?'), this.$t('Tips'), {
                confirmButtonText: this.$t('confirm'),
                cancelButtonText: this.$t('cancel'),
                type: 'warning'
            }).then(() => {
                this.syncVisible = false
                this.syncLoading = true
                api.syncData(this.startTime).then(()=> {
                    this.$message({
                        type: 'success',
                        message: this.$t('同步成功!')
                    })
                    this.loadTableData()
                    this.syncLoading = false
                }).catch(() => {})
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: this.$t('已cancel同步')
                })        
            })
        }
    }

}
</script>
